/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package mx.unam.aragon.domain.persistence;

import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;

import javax.persistence.Persistence;

public class AppEntityManagerFactory {
private static EntityManagerFactory emf;    
    private final static Logger log = Logger.getLogger(AppEntityManagerFactory.class.getName());
    
    public static EntityManagerFactory entityManagerFactory() {
        try {
            // assuming single threaded startup
            long begin = System.currentTimeMillis();
            if (emf == null) {
                emf = Persistence.createEntityManagerFactory("scholar");
                log.log(Level.WARNING, "EntityManagerFactory ( singleton ) created for {0}ms", (System.currentTimeMillis() - begin));
            }
            return emf;
        } catch (RuntimeException e) {
            log.log(Level.SEVERE, "Couldn't create EntityManagerFactory: " + e.getMessage(), e);
            throw e;
        } catch (Error e) {
            log.log(Level.SEVERE, "Couldn't create EntityManagerFactory: " + e.getMessage(), e);
            throw e;
        }
    }

    public interface EmTemplate<T> {
        T execute(EntityManager em);
    }

    public static <T> T inTransacion(EmTemplate<T> template) {
        EntityManager entityManager = entityManagerFactory().createEntityManager();
        entityManager.getTransaction().begin();
        T result = template.execute(entityManager);
        entityManager.getTransaction().commit();
        return result;
    }
}
